package com.dxd.onlineshop.mapper;

import com.dxd.onlineshop.pojo.Cart;
import com.dxd.onlineshop.pojo.User;
import org.apache.ibatis.annotations.*;
import com.dxd.onlineshop.pojo.Order;
import com.dxd.onlineshop.pojo.OrderItem;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface UserMapper {
    //获取用户信息
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(int id);

    //获取用户余额
    @Select("SELECT balance FROM users WHERE id = #{id}")
    int getUserBalanceById(int id);

    // 扣除余额
    @Update("UPDATE users SET balance = balance - #{amount} WHERE id = #{userId} AND balance >= #{amount}")
    int deductBalance(@Param("userId") Integer userId, @Param("amount") int amount);

    // 增加余额（充值）
    @Update("UPDATE users SET balance = balance + #{amount} WHERE id = #{userId}")
    int addBalance(@Param("userId") Integer userId, @Param("amount") int amount);


    //更新用户信息
    int updateUser(User user);

    //获取用户购物车信息(多表联查)
    @Select("SELECT c.cart_id, c.user_id, c.product_id, c.quantity, " +
            "p.name as productName, p.price as productPrice, p.image_url as productImage " +
            "FROM cart c " +
            "JOIN products p ON c.product_id = p.id " +
            "WHERE c.user_id = #{userId}")
    List<Cart> getUserCartInfo(Integer userId);

    //更新用户购物车商品数量
    @Update("UPDATE cart SET quantity = #{quantity} WHERE cart_id = #{cartId} AND user_id = #{userId}")
    int updateCartItemQuantity(@Param("cartId") Integer cartId, @Param("userId") Integer userId, @Param("quantity") Integer quantity);

    // 从购物车中删除商品
    @Delete("DELETE FROM cart WHERE cart_id = #{cartId} AND user_id = #{userId}")
    int removeCartItem(@Param("cartId") Integer cartId, @Param("userId") Integer userId);

    // 清空用户的购物车
    @Delete("DELETE FROM cart WHERE user_id = #{userId}")
    int removeCart(@Param("userId") Integer userId);

    // 添加商品到购物车
    @Insert("INSERT INTO cart (user_id, product_id, quantity) VALUES (#{userId}, #{productId}, #{quantity})")
    @Options(useGeneratedKeys = true, keyProperty = "cartId")
    int addCartItem(Cart cart);

    //获得对应商品所在购物车(扫描商品)
    @Select("SELECT * from cart where product_id = #{productId} and user_id = #{userId}")
    Cart getCartId(@Param("productId") Integer productId, @Param("userId") Integer userId);

//    -----------------------------------------------订单服务-----------------------------------------------

    // 创建新订单
    @Insert("INSERT INTO orders (user_id, order_number, total_amount, order_status, created_at, updated_at) " +
            "VALUES (#{userId}, #{orderNumber}, #{totalAmount}, #{orderStatus}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "orderId")
    int createOrder(Order order);

    // 添加订单项
    @Insert("INSERT INTO orderitems (order_id, product_id, quantity, unit_price, subtotal) " +
            "VALUES (#{orderId}, #{productId}, #{quantity}, #{unitPrice}, #{subtotal})")
    @Options(useGeneratedKeys = true, keyProperty = "orderItemId")
    int addOrderItem(OrderItem orderItem);

    // 获取用户的所有订单
    @Select("SELECT * FROM orders WHERE user_id = #{userId}")
    @Results({
            @Result(property = "orderId", column = "order_id"),
            @Result(property = "orderItems", column = "order_id",
                    many = @Many(select = "getOrderItemsByOrderId"))
    })
    List<Order> getUserOrders(Integer userId);

    // 获取订单的所有商品
    @Select("SELECT * FROM orderitems WHERE order_id = #{orderId}")
    List<OrderItem> getOrderItemsByOrderId(Integer orderId);

    // 更新订单状态
    @Update("UPDATE orders SET order_status = #{orderStatus}, updated_at = #{updatedAt} WHERE order_id = #{orderId}")
    int updateOrderStatus(@Param("orderId") Integer orderId, @Param("orderStatus") Order.OrderStatus orderStatus, @Param("updatedAt") LocalDateTime updatedAt);

    //获取单个订单详情(根据订单编号)
    @Select("SELECT * FROM orders WHERE order_id = #{orderId}")
    @Results({
            @Result(property = "orderId", column = "order_id"),
            @Result(property = "orderItems", column = "order_id",
                    many = @Many(select = "getOrderItemsByOrderId"))
    })
    Order getOrderById(Integer orderId);

    // 删除订单（可选，取决于您的业务需求）
    @Delete("DELETE FROM orders WHERE order_id = #{orderId}")
    int deleteOrder(Integer orderId);

    // 删除订单项（可选，通常与删除订单一起使用）
    @Delete("DELETE FROM orderitems WHERE order_id = #{orderId}")
    int deleteOrderItems(Integer orderId);

}